<template>
  <view class="login">
    <view class="login_logo">
      <u--image width="220rpx" height="220rpx" mode="aspectFit" src="/static/logo.png"/>
    </view>
    <view class="login_tit login-title-color u-text-center">{{ title }}</view>
    <view class="login-form" v-if="showLoginForm">
      <uni-forms ref="loginForm" :model="loginForm" :rules="loginRules" validate-trigger="bind">
        <uni-forms-item name="loginName">
          <uni-easyinput prefixIcon="account-fill" trim type="text" v-model="loginForm.loginName" placeholder="请输入用户名" />
        </uni-forms-item>
        <uni-forms-item name="password">
          <uni-easyinput prefixIcon="lock-opened-fill" type="password" v-model="loginForm.password" placeholder="请输入密码"/>
        </uni-forms-item>
        <uni-forms-item style="width: 25%">
          <checkbox :checked="rememberPassword" @click="rememberPassword =!rememberPassword">
            <text class="u-font-md">记住我</text>
          </checkbox>
        </uni-forms-item>
        <uni-forms-item>
          <u-button :loading="loading" loadingText="登录中" color="#4870da" @click="handleLogin">登录</u-button>
        </uni-forms-item>
      </uni-forms>
    </view>
    <view v-else class="login-form u-p-t-80 u-p-b-40">
      <u-button :loading="loading" loadingText="登录中" color="#4870da" @click="handleWxLogin">微信登录</u-button>
    </view>
    <view class="login-btn u-p-t-10 u-p-b-10 u-p-l-20 u-p-r-20">
      <view class="u-font-26 u-p-l-20">环境:{{env}}</view>
      <view class="u-font-26 u-p-l-20">版本号:{{appVersion}}</view>
    </view>
  </view>
</template>

<script>
import { storageUtils } from '@utils/storage';
import { getSession } from '@api/sys/users';

export default {
  name: 'login',
  data() {
    return {
      appVersion: process.env.VUE_APP_VERSION,
      // 环境
      env: process.env.VUE_APP_MODE,
      title: 'XXXXXX系统',
      showLoginForm: true,
      loading: false,
      loginForm: {
        userType: '4',
        loginName: '',
        password: ''
      },
      rememberPassword: true,
      loginRules: {
        loginName: {
          rules: [
            { required: true, errorMessage: '请输入用户名' },
            { min: 2, max: 20, errorMessage: '长度在2到20个字符' }
          ]
        },
        password: {
          rules: [{ required: true, errorMessage: '请输入密码' }]
        }
      }
    }
  },
  mounted() {
    const rememberPassword = uni.getStorageSync('rememberPassword');
    console.log('rememberPassword', rememberPassword);
    this.rememberPassword = rememberPassword === true || rememberPassword === '';

    if (rememberPassword === true) { // 页面加载时获取本地存储的密码
      const password = uni.getStorageSync('password');
      const loginName = uni.getStorageSync('loginName');
      console.log('缓存的密码:', password)
      if (password && loginName) {
        this.loginForm.password = password;
        this.loginForm.loginName = loginName;
      }
      const user = storageUtils.getLocalItem('LOGINUSER');
      console.log('缓存的user', user)
      if (user) {
        this.loginForm.loginName = user.userAccount ? user.userAccount : ''
        this.loginForm.userType = user.userType ? user.userType.toString() : '2'
      }
    }
  },

  methods: {
    handleLogin() {
      this.$refs.loginForm.validate().then(() => {
        this.loading = true;
        this.$store.dispatch('user/login', this.loginForm).then(res => {
          if (res && res.success) {
            this.loading = false;
            uni.setStorageSync('rememberPassword', this.rememberPassword);
            uni.setStorageSync('userType', this.loginForm.userType);
            if (this.rememberPassword) {
              uni.setStorageSync('password', this.loginForm.password);
              uni.setStorageSync('loginName', this.loginForm.loginName);
            } else { // 销毁缓存中的账号、密码
              uni.removeStorageSync('password');
              uni.removeStorageSync('loginName');
            }
            uni.switchTab({
              url: '/pages/tabBar/home'
            })
          } else {
            uni.showModal({
              title: '提示',
              content: res.message,
              showCancel: false
            });
          }
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        })
      })
    },
    handleWxLogin() {
      this.loading = true;
      uni.login({
        provider: 'weixin',
        success: res => {
          getSession(res.code).then(result => {
            const { success, data, message } = result;
            if (success) {
              Object.assign(this.loginForm, { openid: data.openid })
              this.loginByOpenid(data.openid);
            } else {
              this.loading = false;
              uni.showModal({
                showCancel: false,
                content: String(message)
              })
            }
          })
        },
        fail: err => {
          this.loading = false;
          uni.showModal({
            showCancel: false,
            content: String(err)
          })
        }
      })
    },
    loginByOpenid(openid) {
      this.$store.dispatch('user/loginByOpenid', { openid }).then(res => {
        if (res && res.success) {
          const redirect = storageUtils.getLocalItem('REDIRECT');
          if (redirect) {
            uni[redirect.type](redirect);
            storageUtils.removeLocalItem('REDIRECT');
          } else {
            uni.switchTab({
              url: '/pages/tabBar/home'
            })
          }
        } else {
          this.showLoginForm = true;
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  background-color: #ffffff;
  .login_logo {
    width: rpx(300);
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    padding: 100rpx 0 30rpx 0;
  }
  .login-title-color {
    color: #4870da;
  }
  .login_tit {
    padding: rpx(40) 0;
    font-weight: bold;
  }
  .login-form {
    width: 80%;
    margin: 0 auto;
  }
  .login-btn {
    display: flex;
    position: fixed;
    justify-content: center;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 99;
    //background-color: #3c9cff;
    color: #4870da;
    text-align: center;
  }
}
</style>
